package org.springboot.redis.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springboot.redis.entity.Book;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Repository;

@Repository
@CacheConfig(cacheManager = "FirstCacheManager")
public class RedisCacheDao {
	
	private static final Logger logger = LoggerFactory.getLogger(RedisCacheDao.class);

	@Cacheable(cacheNames = "book", key = "#p0", cacheManager = "FirstCacheManager")
    public Book getByIsbn(String isbn) {
        simulateSlowService();
        return new Book(isbn, "Some book");
    }
	
	/**
	 * 指定 key，将更新的结果同步到redis中
	 * @param isbn
	 */
	@CachePut(cacheNames = "book", key = "#p0")
	public Book putByIsbn(String isbn) {
        simulateSlowService();
        return new Book(isbn, "Some book !");
    }
	
	/**
	 * 指定 key，清空 redis 缓存
	 * @param isbn
	 * @return
	 */
	@CacheEvict(cacheNames = "book", key = "#isbn", allEntries = false)
	public String evictByIsbn(String isbn) {
        return "success";
    }
	
	/**
	 * 当指定了 allEntries 为 true 时，Spring Cache 将忽略指定的 key
	 * @param isbn
	 * @return
	 */
	@CacheEvict(cacheNames = "book", key = "#isbn", allEntries = true)
	public String evictAll(String isbn) {
        return "success";
    }
	
	/**
	 * 模仿数据库查询
	 */
    private void simulateSlowService() {
        try {
        	logger.info("select data !");
            long time = 2000L;
            Thread.sleep(time);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
    }
}
